package com.xujianlun.cpms.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xujianlun.cpms.entity.sys.User;
import com.xujianlun.cpms.service.sys.IUserService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * @version 1.0
 * @Author xujianlun
 * @Date 2022/5/9 19:54
 * @注释
 */
public class TokenUtil {

    private static IUserService staticUserService;
    @Resource
    private IUserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }
    // 签名密钥
    private static final String SECRET = "!DAR$";
    /**
     * 生成token
     */
    public static String getToken(String userId,String sign){
        return JWT.create().withAudience(userId)//将userId到token作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),7))//7小时token过期
                .sign(Algorithm.HMAC256(sign));//以password作为token的密钥
    }
    /**
     * 解析token
     * @param token token字符串
     * @return 解析后的token
     */
    public static DecodedJWT decode(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT;
    }

    /**
     * 获取当前登录的用户信息
     * @return user对象
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    /**
     * 获取userId
     * @return
     */
    public static Integer getTokenUserId() {
        String token = getRequest().getHeader("token");// 从 http 请求头中取出 token
        Integer userId = Integer.valueOf(JWT.decode(token).getAudience().get(0));
        return userId;
    }
    /**
     * 获取request
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }
}
